/*
 * Copyright (C) 2012 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.demo.ui;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.RadioButton;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;

import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.Utils;
import com.mol.market.demo.widget.BaseFragmentActivity.KeyStore;
import com.mol.market.demo.widget.CommonAdapter;
import com.mol.market.demo.widget.ListFragmentWrapper;

/**
 * 游戏/应用 分类
 * @author Chaos	
 * @Description TODO
 * @date 2013-1-18 
 */
public class CategoryWithHeaderFragment extends ListFragmentWrapper implements OnItemClickListener{

    private String mCurTag = null;

    @Override
    protected View onCreateViewPort(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        
        return super.onCreateViewPort(inflater, container, savedInstanceState);
    }
    
    @Override
    protected void initAbsListView(AbsListView absListView) {
        super.initAbsListView(absListView);
        absListView.setOnItemClickListener(this);
    }

    @Override
    protected void doLoad() {
        MarketAPI.getAllCategory(getApplicationContext(), this);
    }

    @Override
    protected ListAdapter initAdapter() {
    	String lan = Locale.getDefault().getLanguage();
    	String[] tmp = null;
    	if("zh".equals(lan)) {
    		tmp = new String[] {
                    Constants.KEY_CATEGORY_ICON_URL, 
                    Constants.KEY_CATEGORY_NAME,
                    };
    	} else {
    		tmp = new String[] {
                    Constants.KEY_CATEGORY_ICON_URL,
//                    Constants.KEY_CATEGORY_NAME, 
                    Constants.KEY_CATEGORY_ENNAME,
                    };
    	}
        CommonAdapter adapter = new CommonAdapter(
                this, 
                null,
                R.layout.fragment_category_list_item,
                tmp, 
                new int[] {
                        R.id.iv_icon, 
                        R.id.tv_category_name,
                        }
        );
        return adapter;
    }
    
    @Override
    public void onSuccess(int method, Object obj) {
        super.onSuccess(method, obj);
        
        if(getAdapter() != null){
            ((CommonAdapter)getAdapter()).addData(update(parseTag(mCurTag), (ArrayList<HashMap<String, Object>>)obj));
        }
    }
    
    private String parseTag(String tag){
        
        tag = getArguments().getString(KeyStore.KEY_ARG);
        
        if(tag.equals(KeyStore.TARGET_CATEGORY_APP)){
            return "应用";
        }else if (tag.equals(KeyStore.TARGET_CATEGORY_GAME)){
            return "游戏";
        }else{
            return null;
        }
    }
    
    private ArrayList<HashMap<String, Object>> update(String tag, ArrayList<HashMap<String, Object>> data) {
        /*
         * step.1:服务器传回的数据包含了二级分类信息，0.9.6要求取消二级分类信息，
         *        所以我们要对信息进行判断，如果包含分类信息，则将分类信息展示到
         *        一个新的GridView上，并在其之上添加一个Separator. 
         * step.2:如果进行了step.1，则需要在data中去除信息，避免重复显示。
         * 
         * notice:data将被缓存，使用的依然是data的引用，所以不可以直接修改data，
         *        否则将会对 Adapter产生影响。
         */

        //copying data is for reuse, and shallow copy is enough
        ArrayList<HashMap<String, Object>> garbage = (ArrayList<HashMap<String, Object>>) data.clone();
        if (garbage.size() == 0) {
            //The server returned empty data
            this.onError(MarketAPI.ACTION_GET_ALL_CATEGORY, 0);
            return null;
        }
        
        //将电子书置于最后的位置，这里将电子书相关信息保存下来
        String eBook = "电子书";

        //handle data
        for (HashMap<String, Object> item : data) {
            Object subData = item.get(Constants.KEY_SUB_CATEGORY);
            if (subData != null) {
                // 含有二级分类
                String subCategoryName = (String) item.get(Constants.KEY_CATEGORY_NAME);
                if(eBook.equals(subCategoryName)){
                    //如果是电子书 ，保存起来
                    garbage.remove(item);
                    continue ;
                }
                if(subCategoryName.equals(tag)){
                   return (ArrayList<HashMap<String, Object>>) subData;
                }
                garbage.remove(item);
                
            }
        }

        //using "garbage" init
        return garbage;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object metadata = parent.getAdapter().getItem(position);
        @SuppressWarnings("unchecked")
        HashMap<String, Object> item = (HashMap<String, Object>) metadata;
        String categoryId = (String) item.get(Constants.KEY_CATEGORY_ID);
        
        String categoryName = null;
    	String lan = Locale.getDefault().getLanguage();
        if("zh".equals(lan)) {
        	categoryName = (String) item.get(Constants.KEY_CATEGORY_NAME);
        } else {
        	categoryName = (String) item.get(Constants.KEY_CATEGORY_ENNAME);
        }
        
        Utils.jumpToPage(getActivity(), TabFragmentActivity.class, false, 
                new String[]{
                    KeyStore.KEY_ENTRY,
                    Constants.EXTRA_CATEGORY_ID,
                    KeyStore.KEY_TITLE
                }, 
                new Serializable[]{
                    KeyStore.TARGET_CATEGORY_TAB_LIST,
                    categoryId,
                    categoryName
                });
    }
    
    @Override
    protected ViewGroup getCommonList(LayoutInflater inflater) {
    	ViewGroup vg = (ViewGroup) inflater.inflate(R.layout.category_with_header, null);
		RadioButton rb1 = (RadioButton) vg.findViewById(R.id.rb_all);
		RadioButton rb2 = (RadioButton) vg.findViewById(R.id.rb_type);
		rb2.setChecked(true);
		rb1.setOnClickListener(this);
		rb2.setOnClickListener(this);
        return vg;
    }
    
	@Override
	public void onClick(View v) {
		super.onClick(v);
		((HomeFragmentActivity)getActivity()).setGameTabPos(HomeFragmentActivity.TAB_GAME);
	}
}
